<template>
  <div>
    <RePage>
      <div class="pl-[0px]">
        <MyFormCreate :clear-event="getTableList" v-model="searchFrom" :rule="searchFormRules" :key="key">
          <el-button type="primary" @click="DebounceGetTableList">搜索</el-button>
          <sj-button custom-type="sinfo" @click="DebounceResetting">重置</sj-button>
        </MyFormCreate>
        <div>
          <el-button v-auth="'system.project-user.create'" type="primary" :icon="Plus" @click="add">授权用户</el-button>
          <!-- <el-button type="danger" :icon="Delete" :disabled="!selectionData.length" @click="deletes()">批量删除</el-button> -->
        </div>
        <pure-table class="mt-5" :data="tableData.data" :columns="initPureTableConfig(roleTableConfig)" showOverflowTooltip border
          @selection-change="selectionChange" :isShowPag="false">
          <template #roles="{ row }">

            <el-tag class="mr-[10px]" v-for="(item, index) in row.roles" :key="index">{{ isNullOrEmpty( item.roleName ) }}</el-tag>

          </template>
          <template #action="{ row }">
            <el-space>
              <sj-link custom-type="sblue" :underline="false" @click="edit(row)" :disabled="isDisabled(row.unityId)"
                v-auth="'system.project-user.modify'">编辑</sj-link>
              <sj-link custom-type="sred" :underline="false" @click="deletes(row)"
                v-auth="'system.project-user.delete'">删除</sj-link>
            </el-space>
          </template>
        </pure-table>
        <div class="mt-5">
          <el-pagination v-model:current-page="searchFrom.page" v-model:page-size="searchFrom.limit" background
            :layout="PAGE_LAYOUT" :total="tableData.total" @size-change="getTableList" @current-change="getTableList" />
        </div>
      </div>



    </RePage>
  </div>
</template>
<script lang="ts" setup>
import {isNullOrEmpty,initPureTableConfig} from '@/utils/functions'
import { ContextProps } from "@/components/ReSplitPane";
import MyFormCreate from "@/components/MyFormCreate/index.vue";
import RePage from "@/components/RePage/index.vue";
import editForm from "./form.vue";
import infos from "./info.vue";
import { reactive, ref, h } from "vue";
import { PAGE_LAYOUT, PAGE_LAYOUTLEFT } from "@/constant";
import { Plus, } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getList,
  getInfo,
  addInfo,
  editInfo,
  deleteInfo
} from "@/api/manage/projectManagementes/user-authorization/index";
import { getList as projectLists } from '@/api/manage/projectManagementes/projectManagementes/index';
import { titles, defaultSearchForm, prompt, defaultInfoForm } from "./index";
import { addDialog } from "@/components/ReDialog";
import {
  deviceDetection,
  debounce
} from "@pureadmin/utils";
import { message } from "@/utils/message";
import { customPromiseDebounce, isDisabled } from "@/utils/functions";
import { usePageVariablesStoreHook } from '@/store/modules/pageVariables'
const manage = usePageVariablesStoreHook().getManage()
console.log("manage,", manage);

const projectID = ref();//用于重置时项目id不重置
const productName = ref();//用于from回显
const projectList = ref([]);
const isLoading = ref(true);
const treeListRef = ref()
const searchFrom = ref(defaultSearchForm());
const key = ref(0);
const showInfo = ref();
const formRef = ref();
const tableData = reactive({
  data: [],
  total: 0
});
const projectDefultSearch = () => { // 数分页参数
  return {
    limit: 10,
    page: 1
  };
};
const treeListPage1 = ref(projectDefultSearch());// 数分页参数
const searchFormRules = [
  {
    type: "input",
    field: "userName",
    title: titles.userName,
    value: null,
    props: {
      placeholder: prompt.userNames,
      clearable: true
    }
  },
  {
    type: "input",
    field: "projectName",
    title: "项目名称",
    value: null,
    props: {
      placeholder: "请输入项目名称",
      clearable: true
    }
  },
  {
    type: "input",
    field: "phone",
    title: titles.phone,
    value: null,
    props: {
      placeholder: prompt.phone,
      clearable: true
    }
  },
  { type: "number", field: "page", title: "page", hidden: true },
  { type: "number", field: "limit", title: "limit", hidden: true }
];
const selectionData = ref([]);
const roleTableConfig = [
    { prop: "id", label: titles.id, width:  100,  fixed: 'left' },
    { prop: "projectName", label: titles.projectName, minWidth: 150 },
    { prop: "userName", label: '授权用户', minWidth: 100 },
    { prop: "projectUnityName", label: '项目所属单位', minWidth: 150 },
  { prop: "unityName", label: '用户所属单位', minWidth: 150 },
  { prop: "phone", label: titles.phone, minWidth: 120 },

  { slot: "roles", label: titles.roles, minWidth: 150 },
  { slot: "action", label: titles.action, width: 100, fixed: "right" }
];
onMounted(() => {
  getTableList();
  // loadProjectList();
  // treeRef.value = treeListRef.value.getTreeRef();// 获取tree实例
  //   loadProjectList().then(() => {
  //     treeListRef.value.getTreeRef().setCurrentKey(projectList.value[0].id);
  //     searchFrom.value.projectId = projectList.value[0].id
  //     getTableList()
  // });
});
//ce
const props = { //树参数
  label: "projectName",
  id: "id",
  isLeaf: "isLeaf"
};
const filterMethod = (query, node) => {

  return node.projectName.includes(query);
};
//侧边栏搜索框
const inputChange = e => {
  console.log(e, 88888);
  treeListRef.value.getTreeRef().filter(e);

};
const loadProjectList = () => {
  return new Promise((resolve) => {
    isLoading.value = true;
    projectLists(treeListPage1.value)
      .then(res => {
        // projectList.value.unshift({
        //   id: null,
        //   projectName: "全部",
        //   children: []
        // });
        let arr = [
          {

            id: 0,
            projectName: "全部",

          }
        ]
        res.result.data.unshift(...arr);
        projectList.value = res.result.data;
        pageProops.value.total = res.result.total;

      })
      .finally(() => {
        isLoading.value = false;
        resolve('');
      });
  });
};


const pageProops = ref({
  layout: PAGE_LAYOUTLEFT,
  total: 0,
  "pager-count": "3"
})
const handleNodeClick = data => {


  projectID.value = data.id;
  searchFrom.value.projectId = data.id;
  productName.value = data.projectName;
  DebounceGetTableList()

};
const pageChange = e => {  //分页事件
  loadProjectList();
  console.log('page-change', e);

}


// 获取列表数据
const getTableList = () => {
  getList(searchFrom.value).then(res => {
    if (res.code === 200) {
      tableData.data = res.result.data;
      tableData.total = res.result.total;
    }
  });
};
// 重置搜索栏
const resetting = () => {
  //点击重置按键
  Object.assign(searchFrom.value, defaultSearchForm());
  searchFrom.value.projectId = projectID.value //重置时项目id不重置
  key.value++;
  getTableList();
};
// 详情
// 新增
const add = () => {
  showInfo.value = {};
  openDialog();
};
// 编辑
const edit = row => {
  showInfo.value = {};
  openDialog("编辑用户授权", row);
};
// 删除
const deletes = (row?) => {
  ElMessageBox.confirm(`确认删除${row ? "当前" : "选中的"}数据?`, "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteInfo({
      ids: row ? [row.id] : selectionData.value.map(item => item.id)
    }).then(res => {
      if (res.code == 200) {
        ElMessage({
          type: "success",
          message: "删除成功"
        });
        getTableList();
      }
    });
  });
};
// 开启弹窗
const openDialog = (title = "添加项目授权", row?: any) => {
  addDialog({
    title: `${title}`,
    width: "800px",
    draggable: true,
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false,
    contentRenderer: () => h(editForm, { ref: formRef }),
    openAutoFocus({ options }) {
      // console.log("openAutoFocus",row);
      
      if (row) {
        options.props = {
          isLoading: true,
          formInline: defaultInfoForm(),
          projectName: productName.value,
          unityName: row.unityName,
          projectUnityName: row.projectUnityName,
          unityId: row.unityId,
          edit: true
        };
        getInfo({ id: row.id })
          .then(res => {
            if (res.code == 200) {
              showInfo.value = res.result.data;
              options.props.formInline = res.result.data;
            }
          })
          .finally(() => {
            options.props.isLoading = false;
          });
      } else {
        options.props = {
          isLoading: false,
          formInline: defaultInfoForm(),
          projectName: productName.value,
          unityName: usePageVariablesStoreHook().getManage().unityName,
          unityId: usePageVariablesStoreHook().getManage().unityId,
       
          edit: false
        };
      }
    },
    beforeSure: (done, { options }) => {
      const FormRef = formRef.value.getRef();
      const formData = options.props.formInline;

      
      function chores() {
        message(`操作成功`, {
          type: "success"
        });
        done(); // 关闭弹框
        getTableList(); // 刷新表格数据
      }
      FormRef.validate(valid => {
        if (valid && !options.props?.isLoading) {
          // console.log("formData", formData);
          // 表单规则校验通过
          options.props.isLoading = true;
          if (title === "添加项目授权") {
            formData.unityId = manage.unityId
            searchFrom.value.projectId = projectID.value
            DebounceAddInfo({ ...formData, projectId: searchFrom.value.projectId })
              .then(res => {
                if (res.code == 200) {
                  chores();
                }
                options.props.isLoading = false;
              })
              .catch(err => {
                if (err !== "请求中") {
                  options.props.isLoading = false;
                }
              });
          } else {
            formData.projectId = row.projectId
            formData.unityId = row.unityId
            DebounceEditInfo(formData)
              .then(res => {
                if (res.code == 200) {
                  chores();
                }
                options.props.isLoading = false;
              })
              .catch(err => {
                if (err !== "请求中") {
                  options.props.isLoading = false;
                }
              });
          }
        }
      });
    }
  });
};
const selectionChange = data => {
  selectionData.value = data;
};
// 获取列表
const DebounceGetTableList = debounce(getTableList, 1000, true);
// 重置
const DebounceResetting = debounce(resetting, 1000, true);
// 添加请求
const DebounceAddInfo = customPromiseDebounce(addInfo, 1000, true);
// 编辑请求
const DebounceEditInfo = customPromiseDebounce(editInfo, 1000, true);
</script>
<style lang="scss" scoped>
.split-pane {
  width: 100%;
  // min-height: calc(100vh - 200px);
  //   font-size: 50px;
  //   text-align: center;
  //   border: 1px solid #e5e6eb;

  //   .dv-a {
  //     padding-top: 0vh;
  //     color: rgba($color: dodgerblue, $alpha: 80%);
  //   }

  //   .dv-b {
  //     padding-top: 0vh;
  //     color: rgba($color: #000, $alpha: 80%);
  //   }

  //   .dv-c {
  //     padding-top: 0vh;
  //     color: rgba($color: #ce272d, $alpha: 80%);
  //   }
}
</style>
